import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import uni from '@dcloudio/vite-plugin-uni'
import CopyPlugin from 'vite-plugin-files-copy'
import path from 'path'
import { patchAll } from './build_utils/patcher'
// import fs from 'fs-extra'

const ENV_PREFIX = 'HC_'
patchAll(ENV_PREFIX)

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: [
      {
        find: '@',
        replacement: path.resolve(__dirname, 'src'),
      },
    ],
  },
  envPrefix: ENV_PREFIX,
  plugins: [
    uni(),
    AutoImport({
      include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
      imports: ['vue'],
    }),
    CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'src', 'certificate'),
          to: process.env.UNI_OUTPUT_DIR as string,
        },
      ],
    }),
    // copyFile(),
  ],
  build: {
    ...(process.env.NODE_ENV === 'production' && {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
        },
      },
    }),
  },
})

// function copyFile() {
//   return {
//     enforce: 'post',
//     async writeBundle() {
//       try {
//         await fs.copy(
//           path.resolve(__dirname, 'src', 'wxcomponents'),
//           path.join(
//             __dirname,
//             'dist',
//             process.env.NODE_ENV === 'production' ? 'build' : 'dev',
//             process.env.UNI_PLATFORM as string,
//             'wxcomponents'
//           )
//         )
//       } catch (e) {
//         console.warn(e)
//       }
//     },
//   }
// }
